'''
Created on Aug 19, 2013

@author: Cihat Basol
'''


from flask.ext.wtf.form import Form
from wtforms.fields import TextField, PasswordField
from wtforms import validators


class LoginForm(Form):
    username = TextField(validators=[validators.required()])
    password = PasswordField(validators=[validators.required()])

    def __init__(self, user_mgr, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)
        self.user_mgr = user_mgr

    def validate(self):
        rv = super(LoginForm, self).validate()

        user = self.get_user()
        if user is None:
            return False
            raise validators.ValidationError('Invalid user')
        
        if user.password != self.password.data:
            return False
            raise validators.ValidationError('Invalid password')
        
        return True

    def get_user(self):
        return self.user_mgr.get_user(username=self.username.data)


class RegistrationForm(Form):
    username = TextField(validators=[validators.required()])
    password = PasswordField(validators=[validators.required()])

    def __init__(self, user_mgr, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
        self.user_mgr = user_mgr


    def validate(self):
        rv = super(RegistrationForm, self).validate()
        if self.user_mgr.exists(self.username.data):
            return False
            raise validators.ValidationError('Duplicate username')
        return True


